package win.smartown.java.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by smartown on 2017/5/16.
 */
public class FileManager {

    private String root;

    public FileManager(String root) {
        this.root = root;
    }

    public void listFile() throws Exception {
        File directory = checkDirectory();
        if (directory == null) {
            return;
        }
        List<String> fileList = getFiles(directory);
        if (fileList.isEmpty()) {
            System.out.println("directory is empty.");
        } else {
            for (int i = 0; i < fileList.size(); i++) {
                System.out.println((1 + i) + "." + fileList.get(i));
            }
        }
        System.out.println("1.create new file\n2.remove file.");
    }

    private File checkDirectory() {
        File file = new File(root);
        if (file.exists()) {
            if (!file.isDirectory()) {
                System.out.println(root + " is not a directory.");
                return null;
            }
        } else {
            file.mkdirs();
        }
        return file;
    }

    private List<String> getFiles(File directory) {
        List<String> list = new ArrayList<>();
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    list.add(file.getName());
                }
            }
        }
        return list;
    }

}
